/*
 * FormFuncionario.java
 *
 * Created on September 23, 2008, 8:38 PM
 */
package mkt.view;

import java.sql.SQLException;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import mkt.classes.DAO.AvaliacaoDAO;
import mkt.classes.DAO.LivroDAO;
import mkt.classes.bean.Avaliacao;
import mkt.classes.bean.Livro;
import mkt.classes.bean.Usuario;


    /**
 * Classe responsável pelo desenho da tela de cadastro do Funcionário.
 * <br/>
 * São tratados eventos de lostFocus (perda do foco) no campo txtCodigo, os 
 * eventos de acionamento de botões e o duplo click na tabela.
 * @author  mertins
 */
public class FormAvaliacao extends javax.swing.JInternalFrame {

    public JFrame mdi;
    public Usuario usu;

    /**
     * Creates new form FormFuncionario 
     * @param mdi MDI principal.
     */
    public FormAvaliacao(JFrame mdi) {
        this.mdi = mdi;
        initComponents();
        mdi.setLocationRelativeTo(null);
        //tbAvaliacoes.setVisible(false);
        this.atualizaLista();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbAvaliacoes = new javax.swing.JTable();
        btAtualizar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        cmbLivro = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        btSalvar = new javax.swing.JButton();
        btLimpar = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        txtNota = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCodAvaliacao = new javax.swing.JTextField();

        setClosable(true);
        setIconifiable(true);
        setTitle("Controle de Avaliações"); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tbAvaliacoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        tbAvaliacoes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código da Avaliação", "Livro Avaliado", "Nota", "Avaliador"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbAvaliacoes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbAvaliacoesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbAvaliacoes);
        tbAvaliacoes.getColumnModel().getColumn(0).setMaxWidth(80);

        btAtualizar.setText("Atualizar"); // NOI18N
        btAtualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAtualizarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        cmbLivro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel1.setText("Livro:"); // NOI18N

        btSalvar.setText("Salvar"); // NOI18N
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        btLimpar.setText("Limpar"); // NOI18N
        btLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparActionPerformed(evt);
            }
        });

        btExcluir.setText("Excluir"); // NOI18N
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        txtNota.setToolTipText("(1-10)");

        jLabel3.setText("Nota:");

        jLabel2.setText("Codigo:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addGap(22, 22, 22)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbLivro, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNota, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(11, 11, 11))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodAvaliacao, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtCodAvaliacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(cmbLivro, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtNota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btLimpar)
                        .addComponent(btSalvar)
                        .addComponent(btExcluir)))
                .addGap(28, 28, 28))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btAtualizar)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(btAtualizar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
    this.atualizaComboLivro();
    
}//GEN-LAST:event_formInternalFrameOpened

private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
    try {

        Avaliacao ava = new Avaliacao();
        String nota = this.txtNota.getText();
        ava.setNota(Integer.parseInt(nota));
        //escreve o codigo do usuario logado
        //ava.setCodUsuario(usu.getCodusrLogado());
        
        Object obj = this.cmbLivro.getModel().getSelectedItem();
        //pega o nome do livro
        //String titulo = this.cmbLivro.getModel().getSelectedItem().toString();
        if (obj instanceof Livro) {
            //func.setDepartamento((Departamento) obj);
            //liv.setTitulo((Livro) obj);
            ava.setCodLivro(cmbLivro.getSelectedIndex());
        } else {
            JOptionPane.showMessageDialog(this.mdi, "Livro deve ser Informado");
            this.cmbLivro.requestFocus();
            return;
        }
        AvaliacaoDAO avaDAO = new AvaliacaoDAO(TrabalhoMKTMDI.getConexao());
        int cod = this.intCampoTelas(this.txtCodAvaliacao.getText());
        // Escolhe entre atualizar ou criar!
        if (cod > 0) {
            ava.setCod(cod);
            avaDAO.update(ava);
        }
        JOptionPane.showMessageDialog(this.mdi, "Registro Salvo");
        this.limpaTela();
        this.atualizaComboLivro();
        this.atualizaLista();
        //tbAvaliacoes.setVisible(true);        
    } catch (NumberFormatException ex) {
        //verificar se vai ocorrer esta exception e alterar a mensagem!
        JOptionPane.showMessageDialog(this.mdi, "Número mal formatado [Código|Livro]");
        this.txtCodAvaliacao.requestFocus();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao gravar Avaliação:%s", ex.getMessage()));
        Logger.getLogger(FormAvaliacao.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_btSalvarActionPerformed

private void btAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAtualizarActionPerformed
    this.atualizaLista();
}//GEN-LAST:event_btAtualizarActionPerformed

private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparActionPerformed
// TODO add your handling code here:
    this.limpaTela();
    this.txtCodAvaliacao.requestFocus();
}//GEN-LAST:event_btLimparActionPerformed

private void tbAvaliacoesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbAvaliacoesMouseClicked
// TODO add your handling code here:
    
}//GEN-LAST:event_tbAvaliacoesMouseClicked

private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
 try {
        int cod = this.intCampoTelas(this.txtCodAvaliacao.getText());
        if (cod > 0) {
            Avaliacao ava = new Avaliacao(cod);
            AvaliacaoDAO avaDAO = new AvaliacaoDAO(TrabalhoMKTMDI.getConexao());
            avaDAO.delete(ava);
            this.limpaTela();
            this.atualizaLista();
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao excluir Avaliação:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao excluir Avaliação", ex);
    }
    this.atualizaLista();
}//GEN-LAST:event_btExcluirActionPerformed

    /**
     * Método auxiliar para atualizar a JTable com os dados do funcionario
     */
    private void atualizaLista() {
        try {
            AvaliacaoDAO avaDAO = new AvaliacaoDAO(TrabalhoMKTMDI.getConexao());
            List<Avaliacao> lista = avaDAO.listaTodos();
            DefaultTableModel dtm = (DefaultTableModel) this.tbAvaliacoes.getModel();
            dtm.setRowCount(0);
            for (Avaliacao ava : lista) {
                dtm.addRow(new Object[]{ava.getCod(), ava.getCodLivro(), ava.getNota(), ava.getCodUsuario()});
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler Avaliações:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler Avaliações", ex);
        }   
    }
/**
     * Método auxiliar para limpar os campos da tela.
     */
    private void limpaTela() {
        this.txtCodAvaliacao.setText(null);
        this.txtCodAvaliacao.setEnabled(true);
        this.cmbLivro.getModel().setSelectedItem("");
        this.txtNota.setText(null);
    }

    /**
     * Método auxiliar para converter valores String sem causar exceções.
     * @param valor String contendo o valor a ser transformado para número
     * @return O valor convertido em inteiro ou zero em caso de algum problema
     */
    private int intCampoTelas(String valor) {
        int ret = 0;
        try {
            ret = Integer.parseInt(valor);
        } catch (NumberFormatException ex) {
        }
        return ret;
    }

    /**
     * Preenche os campos da tela com informações do funcionário.
     * @param func Funcionario que irá fornecer o código para pesquisa no SGBD e em seguida ir para a tela.
     */
    //departamento -> livro
    //gerente -> genero
    private void atualizaComboLivro() {
        try {
            LivroDAO livDAO = new LivroDAO(TrabalhoMKTMDI.getConexao());
            List<Livro> lista = livDAO.listaTodos();
            Vector v = new Vector(lista);
            v.add(0, "");
            ComboBoxModel cbm = new DefaultComboBoxModel(v);
            this.cmbLivro.setModel(cbm);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler os Livros:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler os Livros", ex);
        }
    }

    @Override
    public void setVisible(boolean aFlag) {
        if (!isVisible()) {
            if (aFlag) {
                this.atualizaComboLivro();
            }
        }
        super.setVisible(aFlag);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAtualizar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btLimpar;
    private javax.swing.JButton btSalvar;
    private javax.swing.JComboBox cmbLivro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbAvaliacoes;
    private javax.swing.JTextField txtCodAvaliacao;
    private javax.swing.JTextField txtNota;
    // End of variables declaration//GEN-END:variables

    
}
